import * as THREE from 'three';
import { gsap } from 'gsap';
import { BaseScene } from './BaseScene.js';

export class GeometryScene extends BaseScene {
    constructor(app, index) {
        super(app, index);
        this.name = '几何场景';
        // 几何体数组
        this.geometries = [];
        this.geometryMeshes = [];
        
        // 场景特定设置
        this.cameraPosition.set(0, 2, 8);
        this.cameraTarget.set(0, 0, 0);
        
        // 动画参数
        this.rotationSpeed = 0.01;
        this.floatAmplitude = 0.5;
        this.floatFrequency = 0.002;
    }
    
    async createObjects() {
        // 创建各种几何体
        this.createGeometries();
        
        // 创建几何体网格
        this.createGeometryMeshes();
        
        // 设置几何体动画
        this.setupGeometryAnimations();
        
        // 创建背景效果
        this.createBackgroundEffects();
    }
    
    createGeometries() {
        // 立方体
        this.geometries.push({
            geometry: new THREE.BoxGeometry(1, 1, 1, 2, 2, 2),
            position: new THREE.Vector3(-3, 0, 0),
            color: 0x667eea,
            name: 'Cube'
        });
        
        // 球体
        this.geometries.push({
            geometry: new THREE.SphereGeometry(0.7, 32, 32),
            position: new THREE.Vector3(0, 0, 0),
            color: 0xf093fb,
            name: 'Sphere'
        });
        
        // 圆环
        this.geometries.push({
            geometry: new THREE.TorusGeometry(0.6, 0.2, 16, 32),
            position: new THREE.Vector3(3, 0, 0),
            color: 0x764ba2,
            name: 'Torus'
        });
        
        // 圆锥
        this.geometries.push({
            geometry: new THREE.ConeGeometry(0.5, 1.5, 8),
            position: new THREE.Vector3(-1.5, 2, -1),
            color: 0xf5576c,
            name: 'Cone'
        });
        
        // 八面体
        this.geometries.push({
            geometry: new THREE.OctahedronGeometry(0.8),
            position: new THREE.Vector3(1.5, 2, -1),
            color: 0x4facfe,
            name: 'Octahedron'
        });
        
        // 圆柱体
        this.geometries.push({
            geometry: new THREE.CylinderGeometry(0.3, 0.5, 1.2, 12),
            position: new THREE.Vector3(0, -2, 0),
            color: 0x43e97b,
            name: 'Cylinder'
        });
    }
    
    createGeometryMeshes() {
        // 获取程序生成的纹理
        const texture = this.app.getResourceLoader().getResource('geometryTexture');
        
        this.geometries.forEach((geomData, index) => {
            // 创建材质
            const material = new THREE.MeshPhongMaterial({
                color: geomData.color,
                map: texture,
                shininess: 100,
                transparent: true,
                opacity: 0.9
            });
            
            // 创建网格
            const mesh = new THREE.Mesh(geomData.geometry, material);
            mesh.position.copy(geomData.position);
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            mesh.userData.name = geomData.name;
            mesh.userData.originalPosition = geomData.position.clone();
            mesh.userData.animationPhase = index * Math.PI / 3;
            
            // 添加到场景
            this.addObject(mesh);
            this.geometryMeshes.push(mesh);
        });
    }
    
    setupGeometryAnimations() {
        // 为每个几何体创建动画对象
        this.geometryMeshes.forEach((mesh, index) => {
            const rotationAxis = new THREE.Vector3(
                Math.random() - 0.5,
                Math.random() - 0.5,
                Math.random() - 0.5
            ).normalize();
            
            const floatPhase = mesh.userData.animationPhase;
            
            const animation = {
                mesh: mesh,
                rotationAxis: rotationAxis,
                floatPhase: floatPhase,
                
                update: ((time) => {
                    // 旋转动画
                    mesh.rotateOnAxis(rotationAxis, this.rotationSpeed);
                    
                    // 浮动动画
                    const floatY = Math.sin(time * this.floatFrequency + floatPhase) * this.floatAmplitude;
                    mesh.position.y = mesh.userData.originalPosition.y + floatY;
                    
                    // 脉冲缩放
                    const scale = 1 + Math.sin(time * 0.003 + floatPhase) * 0.1;
                    mesh.scale.setScalar(scale);
                }).bind(this), // 绑定正确的this上下文
                
                start: () => {
                    // 入场动画
                    gsap.fromTo(mesh.scale, 
                        { x: 0, y: 0, z: 0 },
                        { 
                            x: 1, y: 1, z: 1, 
                            duration: 1.5,
                            delay: index * 0.2,
                            ease: "back.out(1.7)"
                        }
                    );
                },
                
                stop: () => {
                    // 停止时恢复到原始状态
                    gsap.to(mesh.scale, {
                        x: 1, y: 1, z: 1,
                        duration: 0.5
                    });
                }
            };
            
            this.animations.push(animation);
        });
    }
    
    createBackgroundEffects() {
        // 创建背景网格
        this.createBackgroundGrid();
        
        // 创建环绕的粒子
        this.createAmbientParticles();
    }
    
    createBackgroundGrid() {
        const gridSize = 20;
        const divisions = 20;
        
        // 地面网格
        const gridHelper = new THREE.GridHelper(gridSize, divisions, 0x444444, 0x222222);
        gridHelper.position.y = -3;
        gridHelper.material.transparent = true;
        gridHelper.material.opacity = 0.3;
        this.addObject(gridHelper);
        
        // 垂直网格
        const verticalGrid = new THREE.GridHelper(gridSize, divisions, 0x444444, 0x222222);
        verticalGrid.rotation.x = Math.PI / 2;
        verticalGrid.position.z = -5;
        verticalGrid.material.transparent = true;
        verticalGrid.material.opacity = 0.1;
        this.addObject(verticalGrid);
    }
    
    createAmbientParticles() {
        const particleCount = 50;
        const geometry = new THREE.BufferGeometry();
        const positions = new Float32Array(particleCount * 3);
        const colors = new Float32Array(particleCount * 3);
        
        for (let i = 0; i < particleCount; i++) {
            const i3 = i * 3;
            
            // 随机位置
            positions[i3] = (Math.random() - 0.5) * 20;
            positions[i3 + 1] = (Math.random() - 0.5) * 20;
            positions[i3 + 2] = (Math.random() - 0.5) * 20;
            
            // 随机颜色
            const color = new THREE.Color().setHSL(Math.random(), 0.8, 0.6);
            colors[i3] = color.r;
            colors[i3 + 1] = color.g;
            colors[i3 + 2] = color.b;
        }
        
        geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
        geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
        
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: true,
            transparent: true,
            opacity: 0.6
        });
        
        const particles = new THREE.Points(geometry, material);
        this.addObject(particles);
        
        // 粒子动画
        const particleAnimation = {
            particles: particles,
            update: (time) => {
                particles.rotation.y = time * 0.0005;
                particles.rotation.x = time * 0.0003;
            }
        };
        
        this.animations.push(particleAnimation);
    }
    
    adjustParticleCount(factor) {
        // 根据性能调整粒子数量
        const particles = this.objects.find(obj => obj instanceof THREE.Points);
        if (particles && particles.geometry) {
            const originalCount = 50;
            const newCount = Math.floor(originalCount * factor);
            
            // 重新创建粒子系统（简化版）
            if (factor < 1) {
                particles.material.opacity = 0.4 * factor;
            }
        }
    }
    
    updateObjects() {
        super.updateObjects();
        
        // 几何体特定的更新逻辑
        const time = performance.now() * 0.001;
        
        // 更新光照
        if (this.directionalLight) {
            this.directionalLight.position.x = Math.sin(time * 0.5) * 5;
            this.directionalLight.position.z = Math.cos(time * 0.5) * 5;
        }
    }
    
    onResize(width, height) {
        super.onResize(width, height);
        
        // 几何场景特定的响应式调整
        const aspect = width / height;
        
        if (aspect < 1) {
            // 移动设备适配
            this.geometryMeshes.forEach((mesh, index) => {
                const scale = 0.8;
                mesh.scale.setScalar(scale);
            });
        }
    }
}
